/*
	       File: FTPDownload.cs
	Create Date: 2007-12-1
	    Version:

	Description:


*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;

using GuerillaProgrammer.Components;
using GuerillaProgrammer.Components.Logging;
using GuerillaProgrammer.FileProcessor.FTP;

namespace GuerillaProgrammer.FileProcessor.Activities
{
	public partial class FTPDownload: Activity
    {
        #region Private member fields
        private string _SourceDirectory;
        private string _SourceFilename;
        private string _ServerName;
        private string _DownloadDirectory;
        private string _DownloadFilename;
        private string _UserID;
        private string _Password;
        #endregion

        #region Constructors and cleanup methods
        public FTPDownload()
        {
            InitializeComponent();
        }
        #endregion

        #region Private implementation methods
        #endregion

        #region Class properties
        public static DependencyProperty SourceDirectoryProperty = System.Workflow.ComponentModel.DependencyProperty.Register("SourceDirectory", typeof(string), typeof(FTPDownload));
        [Description("Directory to download from.")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string SourceDirectory
        {
            get { return _SourceDirectory; }
            set { _SourceDirectory = value; }
        }
        public static DependencyProperty SourceFilenameProperty = System.Workflow.ComponentModel.DependencyProperty.Register("SourceFilename", typeof(string), typeof(FTPDownload));
        [Description("file to download")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string SourceFilename
        {
            get { return _SourceFilename; }
            set { _SourceFilename = value; }
        }
        public static DependencyProperty ServerNameProperty = System.Workflow.ComponentModel.DependencyProperty.Register("ServerName", typeof(string), typeof(FTPDownload));
        [Description("name of the FTP Server")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string ServerName
        {
            get { return _ServerName; }
            set { _ServerName = value; }
        }
        public static DependencyProperty DownloadDirectoryProperty = System.Workflow.ComponentModel.DependencyProperty.Register("DownloadDirectory", typeof(string), typeof(FTPDownload));
        [Description("Upload directory")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string DownloadDirectory
        {
            get { return _DownloadDirectory; }
            set { _DownloadDirectory = value; }
        }
        public static DependencyProperty DownloadFilenameProperty = System.Workflow.ComponentModel.DependencyProperty.Register("DownloadFilename", typeof(string), typeof(FTPDownload));
        [Description("Download filename")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string DownloadFilename
        {
            get { return _DownloadFilename; }
            set { _DownloadFilename = value; }
        }
        public static DependencyProperty UserIDProperty = System.Workflow.ComponentModel.DependencyProperty.Register("UserID", typeof(string), typeof(FTPDownload));
        [Description("User ID for Download")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string UserID
        {
            get { return _UserID; }
            set { _UserID = value; }
        }
        public static DependencyProperty PasswordProperty = System.Workflow.ComponentModel.DependencyProperty.Register("Password", typeof(string), typeof(FTPDownload));
        [Description("Password")]
        [Category("FTP Download")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string Password
        {
            get { return _Password; }
            set { _Password = value; }
        }
        #endregion

        #region Events handlers
        /// <summary>
        /// Upload the specified file to the directory on the server.
        /// </summary>
        /// <param name="executionContext"></param>
        /// <returns></returns>
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            Logger.LogEnter();
            try
            {
                IProcessorDataService dataService = executionContext.GetService(typeof(IProcessorDataService)) as IProcessorDataService;
                if (null == dataService)
                {
                    throw new InvalidOperationException("Can't get the service!");
                }

                WorkItem workItem = dataService.GetWorkItem();
                StringProcessor stringProcessor = new StringProcessor(new FileProcessorSymbolTable(dataService.GetConfiguration(), workItem));

                string serverName = stringProcessor.SubstituteStringValues(_ServerName);
                string username = stringProcessor.SubstituteStringValues(_UserID);
                string password = stringProcessor.SubstituteStringValues(_Password);

                string sourceDirectory = stringProcessor.SubstituteStringValues(_SourceDirectory);
                string sourceFile = stringProcessor.SubstituteStringValues(_SourceFilename);
                string downloadDirectory = stringProcessor.SubstituteStringValues(_DownloadDirectory);
                string downloadFile = stringProcessor.SubstituteStringValues(_DownloadFilename);
                string downloadFullPath = Path.Combine(downloadDirectory, downloadFile);

                Logger.LogInfo("FTP", "Logging in to server.\nServer: {0}\nUser: {1}\nPassword: yeah right ;)", serverName, username);
                FtpClient ftpClient = new FtpClient(serverName, username, password);

                ftpClient.Login();
                ftpClient.BinaryMode = true;
                Logger.LogInfo("FTP", "Downloading file from server.\nSource File:{0}\nDestination: {1}", Path.Combine(sourceDirectory, sourceFile), downloadFullPath);

                ftpClient.ChangeDir(sourceDirectory);
                ftpClient.Download(sourceFile, downloadFullPath);
                ftpClient.Close();
                Logger.LogInfo("FTP", "Upload complete");

                Logger.LogLeave();
                return base.Execute(executionContext);
            }
            catch (FtpException ftpExc)
            {
                Logger.LogError("FTPclient error", "An error occured during an FTP operation.\nError: {0}", ftpExc.Message);
                Logger.LogLeave();
                return ActivityExecutionStatus.Faulting;
            }
            catch (Exception exc)
            {
                Logger.LogError("FTP Download error", "An error occured during download.\nError: {0}", exc.Message);
                Logger.LogLeave();
                return ActivityExecutionStatus.Faulting;
            }

        }
        #endregion
	}
}
